package cn.shengongying.utils;

import cn.shengongying.exception.BusinessException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpVersion;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * author: RXK
 * date: 2022/1/6 星期四
 * desc:
 */
public class HttpUtils {

    private HttpUtils() {
    }

    public static String postJson(String uri, String params) throws BusinessException {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);
        httpPost.setEntity(new StringEntity(params, ContentType.APPLICATION_JSON));
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try (CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost)) {
            HttpEntity entity = closeableHttpResponse.getEntity();
            return EntityUtils.toString(entity);
        } catch (IOException e) {
            throw new BusinessException("post请求出现异常：{"+e.getMessage()+"}");
        }
    }
}
